<!doctype HTML>
<meta charset = 'utf-8'>
<html>
  <head>
    <link rel='stylesheet' href='/Library/Frameworks/R.framework/Versions/3.0/Resources/library/rCharts/libraries/leaflet/external/leaflet.css'>
    <link rel='stylesheet' href='/Library/Frameworks/R.framework/Versions/3.0/Resources/library/rCharts/libraries/leaflet/external/leaflet-rCharts.css'>
    <link rel='stylesheet' href='/Library/Frameworks/R.framework/Versions/3.0/Resources/library/rCharts/libraries/leaflet/external/legend.css'>
    
    <script src='/Library/Frameworks/R.framework/Versions/3.0/Resources/library/rCharts/libraries/leaflet/external/leaflet.js' type='text/javascript'></script>
    <script src='/Library/Frameworks/R.framework/Versions/3.0/Resources/library/rCharts/libraries/leaflet/external/leaflet-providers.js' type='text/javascript'></script>
    <script src='/Library/Frameworks/R.framework/Versions/3.0/Resources/library/rCharts/libraries/leaflet/external/Control.FullScreen.js' type='text/javascript'></script>
    <script src='regions.js' type='text/javascript'></script>
    
    <style>
    .rChart {
      display: block;
      margin-left: auto; 
      margin-right: auto;
      width: 800px;
      height: 400px;
    }  
    </style>
    
  </head>
  <body>
    <div id='chart9ce53fa5634' class='rChart leaflet'></div>  
    
    <script>
  var spec = {
 "dom": "chart9ce53fa5634",
"width":    800,
"height":    400,
"urlTemplate": "http://{s}.tile.osm.org/{z}/{x}/{y}.png",
"layerOpts": {
 "attribution": "Map data<a href=\"http://openstreetmap.org\">OpenStreetMap</a>\n         contributors, Imagery<a href=\"http://mapbox.com\">MapBox</a>" 
},
"provider": "Stamen.TonerLite",
"center": [    -37,    145 ],
"zoom":      6,
"features": regions,
"legend": {
 "position": "bottomright",
"colors": [ "red", "blue", "green" ],
"labels": [ "high", "medium", "low" ] 
},
"id": "chart9ce53fa5634" 
}
  var map = L.map(spec.dom)
    .setView(spec.center, spec.zoom);

    if (spec.provider){
      L.tileLayer.provider(spec.provider).addTo(map)    
    } else {
		  L.tileLayer(spec.urlTemplate, spec.layerOpts).addTo(map)
    }
     
    
    
    
    
    
    if (spec.circle2){
      for (var c in spec.circle2){
        var circle = L.circle(c.center, c.radius, c.opts)
         .addTo(map);
      }
    }
    
    
    
    
    var geojsonLayer = L.geoJson(spec.features 
        , 
         {
 "style":  function(feature) {
    var rgn2col = {1:'red',2:'blue',4:'green'};     
    return {
      color: rgn2col[feature.properties['region_id']],
      strokeWidth: '1px',
      strokeOpacity: 0.5,
      fillOpacity: 0.2
    }; } ,
"onEachFeature":  function (feature, layer) {

    // info rollover
    if (document.getElementsByClassName('info leaflet-control').length == 0 ){
      info = L.control({position: 'topright'});  // NOTE: made global b/c not ideal place to put this function
      info.onAdd = function (map) {
        this._div = L.DomUtil.create('div', 'info');
        this.update();
        return this._div;
      };
      info.update = function (props) {
      	this._div.innerHTML = '<h4>Field Name</h4>' +  (props ?
      		props['region_id'] + ': <b> + props[fld] + </b>'
      		: 'Hover over a region');
      };
      info.addTo(map);
    };

    // mouse events
    layer.on({

      // mouseover to highlightFeature
  	  mouseover: function (e) {
        var layer = e.target;
        layer.setStyle({
          strokeWidth: '3px',
          strokeOpacity: 0.7,
          fillOpacity: 0.5
        });
      	if (!L.Browser.ie && !L.Browser.opera) {
      		layer.bringToFront();
      	}
	      info.update(layer.feature.properties);
      },

      // mouseout to resetHighlight
		  mouseout: function (e) {
        geojsonLayer.resetStyle(e.target);
	      info.update();
      },

      // click to zoom
		  click: function (e) {
        var layer = e.target;        
        if ( feature.geometry.type === 'MultiPolygon' ) {        
        // for multipolygons get true extent
          var bounds = layer.getBounds(); // get the bounds for the first polygon that makes up the multipolygon
          // loop through coordinates array, skip first element as the bounds var represents the bounds for that element
          for ( var i = 1, il = feature.geometry.coordinates[0].length; i < il; i++ ) {
            var ring = feature.geometry.coordinates[0][i];
            var latLngs = ring.map(function(pair) {
              return new L.LatLng(pair[1], pair[0]);
            });
            var nextBounds = new L.LatLngBounds(latLngs);
            bounds.extend(nextBounds);
          }
          map.fitBounds(bounds);
        } else {
        // otherwise use native target bounds
          map.fitBounds(e.target.getBounds());
        }
      }
	  });
    }  
}
      ).addTo(map)
    
    var legend = L.control({position: spec.legend.position});
    legend.onAdd = function (map) {
      var div = L.DomUtil.create('div', 'info legend'),
          labels = spec.legend.labels,
          colors = spec.legend.colors

      // loop through our density intervals and generate a 
      // label with a colored square for each interval
      for (var i = 0; i < labels.length; i++) {
          div.innerHTML += '<i style="background:' +  colors[i] + '"></i>' + 
            labels[i] + "<br>"
      }
     return div;
    };
    legend.addTo(map); 
   
</script>
    
  </body>
</html>
